//
//  ZDComposeViewController.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/4.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZDComposeViewController: UIViewController {
    
    //toolBar的底部约束
    var toolBarBottomC: NSLayoutConstraint?
    
    //微博字数限制
    let wordsNumberLimit = 20
    
    //photoSelectView的底部约束
    var photoSelectViewBottomC: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        
        prepareUI()
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: textView)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //MARK: - 通知回调方法
    @objc private func textDidChange() {
    
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //已经输入的字符长度
        let writeLength = textView.emojiText().characters.count
        
        //剩余字符长度赋值给label
        let leftLength = wordsNumberLimit - writeLength
        
        wordsTipLabel.textColor = leftLength < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
        wordsTipLabel.text = String(leftLength)
    }
    
    @objc private func keyboardWillChangeFrame(notificaton: NSNotification) {
    
//        print(notificaton)
        
        let dict = notificaton.userInfo!
        
        let duration: NSTimeInterval = (dict[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval)!
        let endFrame = (dict[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
        
//        print("duration = \(duration), endFrame = \(endFrame)")
        
        //修改toolbar的底部约束
        self.toolBarBottomC?.constant = -(UIScreen.height - endFrame!.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            //立即重新布局
            self.view.layoutIfNeeded()

//            self.toolBar.layoutIfNeeded()   //不能是toolBar重新布局
        }
    }
    
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        if photoSelectViewBottomC?.constant != 0 {
        
            textView.becomeFirstResponder()
        }
    }
    
    //MARK: - 准备UI
    private func prepareUI() {
        
        //添加子控件
        view.addSubview(textView)
        
        view.addSubview(photoSelectVC.view)
        
        view.addSubview(toolBar)
        
        view.addSubview(wordsTipLabel)
        
    
        setNavigationBar()
        
        setToolBar()
        
        setTextView()
        
        setWordTipLabel()
        
        setPhotoSelectView()
    }

    //MARK: - 设置导航条
    private func setNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发微博", style: UIBarButtonItemStyle.Done, target: self, action: "sendStatus")
        //默认设置发微博按钮不可用  灰色显示
        navigationItem.rightBarButtonItem?.enabled = false
        
        setTitleView()
    }
    
    //MARK: - 设置中间titleView
    private func setTitleView() {
        
        let name = ZDAccount.loadAccountData()?.name ?? ""
//        let title = "发微博" + "\n" + name
        let title = "发微博\n\(name)"
        let attributeString = NSMutableAttributedString(string: title)
        let range = (title as NSString).rangeOfString(name)
    
        let label = UILabel()
        
//        label.font = UIFont.systemFontOfSize(15)  //默认是18
        //必须设置多行 否则换行不显示
        label.numberOfLines = 0
        label.textAlignment = NSTextAlignment.Center
        
        //设置属性 必须在设置属性文本之前设置属性才有效
//        attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
//        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
        
        
        let attrs = [
        
            NSFontAttributeName : UIFont.systemFontOfSize(15),
            NSForegroundColorAttributeName : UIColor.lightGrayColor(),
        ]
        
        attributeString.addAttributes(attrs, range: range)
        
        
        //设置属性文本
        label.attributedText = attributeString
        
        //设置属性文本后，必须sizeToFit  否则看不到
        label.sizeToFit()
        
        navigationItem.titleView = label
    }
    
    //MARK: - 设置工具条
    private func setToolBar() {
    
//        //添加子控件
//        view.addSubview(toolBar)
        
        //添加约束
        let contraints = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width, height: 44))
        
        //保存底部约束
        toolBarBottomC = toolBar.ff_Constraint(contraints, attribute: NSLayoutAttribute.Bottom)
    }
    
    /*
       iOS中支持文本输入的控件：
       UITextField: 单行输入，不能滚动，有placeholder   继承自UIControl
       UITextView: 多行输入，可以滚动，没有placeholder  继承自UIScrollView
    */
    
    //MARK: - 设置textView
    private func setTextView() {
    
//        //添加子控件
//        view.addSubview(textView)
        
        //添加约束
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
        
    }
    
    //MARK: - 设置WordTipLabel
    private func setWordTipLabel() {
    
//        view.addSubview(wordsTipLabel)
        
        wordsTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    
    //MARK: - 设置photoSelector控制器的view
    private func setPhotoSelectView() {
        
        let photoSelectView = photoSelectVC.view

//        view.addSubview(photoSelectView)
        
        photoSelectView.translatesAutoresizingMaskIntoConstraints = false
        
        //添加约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[svc]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["svc": photoSelectView]))
        
        photoSelectViewBottomC = NSLayoutConstraint(item: photoSelectView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: UIScreen.height * 0.6)
        
        view.addConstraint(photoSelectViewBottomC!)
        
        view.addConstraint(NSLayoutConstraint(item: photoSelectView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
    }
    
    //MARK: - 添加barButtonItems
    private func addBarButtonItems() -> [UIBarButtonItem]? {
    
        var items = [UIBarButtonItem]()
        
        //定义字典数组 保存每一个item的图片名 和 方法名  这样做的好处是直接将方法与item关联，不论item的位置怎么改变，代码都不需要做任何修改；如果通过switch判断button的tag值来处理的话，那么当item位置改变的时候，switch中case的代码也需要改变
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        //遍历
        for dict in itemSettings {
            
            let imageName = dict["imageName"]!
            
            //调用扩展方法 创建barButtonItem
            let item = UIBarButtonItem(imageName: imageName)
            
            //取出barButtonItem中包装的UIButton
            let button:UIButton = item.customView as! UIButton
            
            //取出方法名
            let actionName = dict["action"]!
            
            //Selector(actionName) 将字符串常量转换为Selector  不能直接写字符串常量 或变量  可以写"xxx"
            button.addTarget(self, action: Selector(actionName), forControlEvents: UIControlEvents.TouchUpInside)
            
            //将item添加到数组中
            items.append(item)
            
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        //移除最后一个弹簧
        items.removeLast()
        
        return items
    }
    
    
    //MARK: - 取消按钮点击回调方法
    @objc private func cancel() {
        
        SVProgressHUD.dismiss()
    
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 发微博
    @objc private func sendStatus() {
        
        //拿到textView的文本
        let text = textView.emojiText()
        
        //取出图片选择器的第一张图片
        let image = photoSelectVC.photos.first
        
//        print(text)
        
        if text.characters.count > wordsNumberLimit {
            
            SVProgressHUD.showErrorWithStatus("超出微博内容长度", maskType: SVProgressHUDMaskType.Black)
            
            return
        }
        
        SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
        
        //调用工具类的方法发微博
        ZDNetworkTool.sharedInstance.sendStatus(image, status: text) { (result, error) -> Void in
            
            if error != nil {
            
                print("微博发布失败:\(error)")
                
                SVProgressHUD.showErrorWithStatus("微博发布失败...", maskType: SVProgressHUDMaskType.Black)
                
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布成功", maskType: SVProgressHUDMaskType.Black)
            
            //退出
            self.cancel()
        }
    }
    
    //呼出图片选择器
    @objc private func picture() {
    
        //先退出键盘
        textView.resignFirstResponder()
        
        //修改底部约束
        photoSelectViewBottomC?.constant = 0
        
        //呼出图片选择器
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    
    
    @objc private func trend() {
        
        print("#")
    }
    
    
    @objc private func mention() {
        
        print("@")
    }
    
    
    ///切换到emoji键盘
    @objc private func emoticon() {
        
//        print("切换前inputView:\(textView.inputView)")  //切换前inputView:nil
//        
//        textView.inputView = emojiController.view
//        
//        print("切换后inputView:\(textView.inputView)")  //切换后inputView:Optional(<UIView: 0x7f8c20580cd0...>
        
        /* 以上测试表明：
            inputView为nil表示系统键盘, inputView不为nil表示自定义键盘
            切换键盘后不会立即有效果，需要下次唤出键盘时生效 ———— 每次唤出键盘时根据inputView判断
        */
        
        textView.resignFirstResponder()
        
        //延迟0.25s后呼出键盘 如果没有延迟的话，推出键盘执行完 马上呼出键盘，而键盘的出现与消失的动画是需要时间的，会造成消失与出现的动画叠加 形成跳变效果
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            
            self.textView.inputView = self.textView.inputView == nil ? self.emojiController.view : nil
            
            self.textView.becomeFirstResponder()
        }
    }
    
    
    @objc private func add() {
        
        print("添加")
    }
    
    //MARK: - 懒加载toolBar
    private lazy var toolBar: UIToolbar = {
    
        let toolBar = UIToolbar()
    
        toolBar.barTintColor = UIColor(white: 0.9, alpha: 1.0)
        
         //添加barButtonItems
        toolBar.items = self.addBarButtonItems()
        
        return toolBar
    }()

    //MARK: - 懒加载textView
    private lazy var textView: ZDPlaceholderTextView = {

        let textView = ZDPlaceholderTextView()
    
        textView.backgroundColor = UIColor.whiteColor()
        
        //设置滚动textView时退出键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        //允许textView垂直滚动
        textView.alwaysBounceVertical = true
        
        //设置字体
        textView.font = UIFont.systemFontOfSize(18)
        
        //设置占位文本的内容
        textView.placeholder = "分享新鲜事..."
        
        //设置偏移  如果textView是当前控制器view的第一个子view，那么控制器的automaticallyAdjustsScrollViewInsets属性生效，textView会自动偏移64个点，目的是为了textView的内容不被导航条遮挡  所以不需要再设置contentInset
//        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        return textView
    }()
    
    //MARK: - 懒加载emoji键盘控制器
    private lazy var emojiController: ZDEmojiViewController = {
    
        let controller = ZDEmojiViewController()
        
        //指定emoji键盘输入的textView
        controller.textView = self.textView
        
        return controller
    }()
    
    //MARK: - 懒加载微博字数提示label
    private lazy var wordsTipLabel: UILabel = {
    
        let label = UILabel(fontSize: 12, color: UIColor.blueColor())
        
        //设置默认字数限制 ---- 懒加载里面访问当前对象的属性 必须加self
        label.text = String(self.wordsNumberLimit)
        
        return label
    }()
    
    //MARK: - 懒加载图片选择控制器
    private lazy var photoSelectVC: ZDPhotoSelectorViewController = {
    
        let selectVC = ZDPhotoSelectorViewController()
/*
   //以下终端错误表明  不推荐显示的控制器游离于当前控制器  需要将显示的控制器交由当前控制器管理
   Presenting view controllers on detached view controllers is discouraged <_026SwiftSinaWeiBo.ZDPhotoSelectorViewController: 0x7f9b994c0ea0>
*/
        //添加为当前控制器的子控制器
        self.addChildViewController(selectVC)
        
        return selectVC
    }()
}
